/*
 * Copyright (c) 2025 GuoKaiHong (Shenzhen) Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import util from '@ohos.util';

export default class DataUtil {
  static bytesToHexString(src: number[]) {
    var str = "";
    for (var i = 0; i < src.length; i++) {
      var tmp;
      var num = src[i];
      if (num < 0) {
        //此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
        tmp = (255 + num + 1).toString(16);
      } else {
        tmp = num.toString(16);
      }
      if (tmp.length == 1) {
        tmp = "0" + tmp;
      }
      str += tmp;
    }
    return str;
  }

  static hexStringToBytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
      return null;
    }
    len /= 2;
    var arrBytes = new Array();
    for (var i = 0; i < len; i++) {
      var s = str.substr(pos, 2);
      var v = parseInt(s, 16);
      arrBytes.push(v);
      pos += 2;
    }
    return arrBytes;
  }

  static hexToArr(str) {
    // hex字符串长度通常都是2的倍数，但为了放止意外，判断一下长度，不是2的倍数就在最前面补0
    if (str.length % 2) {
      str = "0" + str
    }
    let arr = []
    for (let i = 0; i < str.length; i += 2) {
      let a = parseInt(str.slice(i, i + 2), 16)
      arr.push(a)
    }
    return arr
  }

  static getUint16Array(uint8Array) {
    return Array.prototype.map
      .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
      .join(',');
  }

  static hexStr2Hex(hex): Uint8Array {
    var bytes: Array<number> = [];
    for (var i = 0; i < hex.length; i += 2) {
      var v = parseInt(hex.substr(i, 2), 16);
      bytes.push(v)
    }
    return new Uint8Array(bytes);
  }

  /**
   * 解析an格式的数据
   *
   * 1）对格式为cn（compressed nemeric,压缩数字）的数据项左靠齐并且右补十六进制‘F’,使数据项的长度达到规定的长度；
   * 2）对格式为an（alphanumeric,字母数字型）的数据项左靠齐并且右补十六进制‘0’,使数据项的长度达到规定的长度；
   */
  static parseFormatANData(data: Uint8Array): string {
    let textDecoder = util.TextDecoder.create('GBK', { fatal: true, ignoreBOM: true });
    try {
      return textDecoder.decodeWithStream(data)
    } catch (e) {
      console.info(e)
      return ""
    }
  }

  static arrToHex(arr) {
    return arr.reduce((accu, item) => {
      let a = item.toString(16)
      if (a.length < 2) {
        a = "0" + a
      }
      a = a.toUpperCase()
      return accu += a
    }, "")
  }

  /**
   * 10进制数字转为16进制字符串
   * @param {number} arg
   * @returns
   */
  static numToHex(arg) {
    try {
      let a = arg.toString(16).toUpperCase();
      return a.length % 2 == 1 ? "0" + a : a;
    } catch (e) {
      console.warn("数字转16进制出错:", e);
    }
  }
}